<template>
  <div class="cart-container" v-loading="loading">
    <el-card v-if="cartItems.length > 0">
      <template #header>
        <div class="cart-header">
          <h2>我的购物车</h2>
          <el-button type="danger" @click="handleClearCart">
            清空购物车
          </el-button>
        </div>
      </template>
      
      <el-table :data="cartItems" style="width: 100%">
        <el-table-column label="图书信息">
          <template #default="{ row }">
            <div class="book-info">
              <img :src="row.book.cover" class="book-cover" />
              <div class="book-details">
                <h4>{{ row.book.title }}</h4>
                <p class="price">¥{{ row.book.price }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="数量" width="200">
          <template #default="{ row }">
            <el-input-number
              v-model="row.quantity"
              :min="1"
              :max="row.book.stock"
              @change="(value) => handleQuantityChange(row.id, value)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="小计" width="150">
          <template #default="{ row }">
            <span class="subtotal">
              ¥{{ (row.book.price * row.quantity).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="handleRemoveItem(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="cart-footer">
        <div class="total">
          总计：<span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <el-button type="primary" size="large" @click="handleCheckout">
          结算
        </el-button>
      </div>
    </el-card>
    
    <el-empty
      v-else
      description="购物车是空的"
      :image-size="200"
    >
      <el-button type="primary" @click="$router.push('/books')">
        去购物
      </el-button>
    </el-empty>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCart, updateCartItem, removeFromCart, checkout } from '@/api/cart'
import type { CartItem } from '@/api/cart'

const router = useRouter()
const cartItems = ref<CartItem[]>([])
const loading = ref(false)

const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.book.price * item.quantity
  }, 0)
})

const loadCart = async () => {
  loading.value = true
  try {
    cartItems.value = await getCart()
  } catch (error) {
    ElMessage.error('获取购物车失败')
  } finally {
    loading.value = false
  }
}

const handleQuantityChange = async (id: number, quantity: number) => {
  try {
    await updateCartItem(id, quantity)
    ElMessage.success('更新数量成功')
  } catch (error) {
    ElMessage.error('更新数量失败')
    loadCart() // 重新加载购物车
  }
}

const handleRemoveItem = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      type: 'warning'
    })
    await removeFromCart(id)
    ElMessage.success('删除成功')
    loadCart()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      type: 'warning'
    })
    for (const item of cartItems.value) {
      await removeFromCart(item.id)
    }
    cartItems.value = []
    ElMessage.success('购物车已清空')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空购物车失败')
    }
  }
}

const handleCheckout = async () => {
  try {
    await checkout()
    ElMessage.success('结算成功')
    router.push('/orders')
  } catch (error) {
    ElMessage.error('结算失败')
  }
}

onMounted(() => {
  loadCart()
})
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.book-cover {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.book-details h4 {
  margin: 0 0 5px 0;
}

.price {
  color: #f56c6c;
  margin: 0;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.total {
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}
</style> 